<template>
  <l-layout class="l-tab-page l-desktop-setting-index">
    <l-panel>
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入名称')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()" btnText="新增配置">
          <el-button-group
            ><l-file-import
              fileType="json"
              classname="SettingImport"
              @success="exportSuccess()"
            ></l-file-import
          ></el-button-group>
        </l-tool-btns>
      </template>
      <div
        class="l-rblock"
        style="padding-bottom: 48px; background-color: #f5f5f5"
        v-loading="tableLoading"
      >
        <div class="l-rblock l-overflow-y">
          <div
            v-show="tableData.length > 0"
            class="l-v-item"
            v-for="item in tableData"
            :key="item.f_Id"
          >
            <el-image
              :src="`${apiUrl}system/annexesfile/${item.f_SchemeId}?token=${token}`"
            >
            </el-image>
            <div class="content__btn" @click="handleDesign(item)">{{ $t('设计') }}</div>
            <div style="position: absolute; top: 8px; right: 8px">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="item.f_EnabledMark"
                @change="handleEnableChange(item)"
              >
              </el-switch>
            </div>
            <div class="content__main">
              <span class="content__name">{{ item.f_Name }}</span>
              <div class="content__menulist">
                <div class="content__view">
                  <el-tooltip :content="$t('删除')">
                    <i class="el-icon-delete" @click="handleDelete(item)"></i>
                  </el-tooltip>
                  <el-tooltip :content="$t('预览')">
                    <i class="el-icon-view" @click="handleViews(item)"></i>
                  </el-tooltip>
                  <el-tooltip :content="$t('复制')">
                    <i
                      class="el-icon-copy-document"
                      @click="handleCopy(item)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip :content="$t('导出')">
                    <i
                      class="learun-icon-vertical-bottom"
                      @click="handleExport(item)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip :content="$t('历史')">
                    <i class="el-icon-time" @click="handleHistory(item)"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
          <el-empty
            v-show="tableData.length == 0"
            :description="$t('暂无数据')"
          ></el-empty>
        </div>
        <div class="l-table--pagination" style="border: 0">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            background
            :page-sizes="[10, 20, 30, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-size="tablePageSize"
            :current-page.sync="tableCurrentPage"
            :total="tableTotal"
          >
          </el-pagination>
        </div>
      </div>
    </l-panel>
    <!--设计-->
    <l-fullscreen-dialog
      :title="$t(formTitle)"
      :headerMidWidth="320"
      :visible.sync="formVisible"
      :isStep="true"
      :steps="['基本配置', '桌面设计']"
      :stepActive.sync="stepActive"
      :validateSteps="handleValidateSteps"
      @ok="handleSave"
      @closed="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <template #headerRight>
        <el-button size="mini" type="warning" @click="handleSave(true)">{{
          $t("暂存")
        }}</el-button>
      </template>
      <my-form ref="form" :stepActive="stepActive"> </my-form>
    </l-fullscreen-dialog>
    <!--预览-->
    <l-fullscreen-dialog
      :title="$t('预览')"
      :visible.sync="preveiwVisible"
      @closed="handleClosePreviewForm"
      @opened="handleOpenedPreviewForm"
      :showOk="false"
    >
      <preview-form ref="previewForm"> </preview-form>
    </l-fullscreen-dialog>
    <!--历史-->
    <l-drawer
      :title="`${$t('历史记录')}-${$t(historyTitle)}`"
      :visible.sync="historyVisible"
      :showOk="false"
      :showClose="false"
      size="640px"
      @opened="HistoryOpened"
    >
      <history
        ref="HistoryForm"
        :schemeInfoId="schemeInfoId"
        :schemeId="schemeId"
        :updateSchemeId="updateSchemeId"
      ></history>
    </l-drawer>
  </l-layout>
</template>
<script>
const api = window.$api.desktop.setting;
import MyForm from "./form";
import PreviewForm from "./previewForm";
import History from "./history";
export default {
  inject: ["admin"],
  components: {
    MyForm,
    PreviewForm,
    History,
  },
  props: {},
  data() {
    return {
      //查询
      searchWord: "",
      searchTableData: null,

      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tablePageSize: 10,
      tableCurrentPage: 1,

      // 设计表单
      stepActive: 0,
      stepPrevBtn: true,
      stepNextBtn: false,
      stepSaveBtn: true,
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,
      formCopy: false,

      preveiwVisible: false,

      historyVisible: false,
      historyTitle: "",
      schemeInfoId: "",
      schemeId: "",
    };
  },
  created() {},
  mounted() {
    this.loadTablePageData();
  },
  computed: {},
  methods: {
    updateModules() {
      this.$store.dispatch("system/module/getList");
    },

    handleCurrentChange(val) {
      this.tableCurrentPage = val;
      this.loadTablePageData(true);
    },
    handleSizeChange(val) {
      this.tablePageSize = val;
      this.loadTablePageData();
    },
    async loadTablePageData(isNotFirst) {
      this.tableLoading = true;
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      const queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateTime DESC",
        f_Name: this.searchWord,
        f_Type: 1,
      };
      const data = await this.$awaitWraper(api.getPage(queryData));
      this.tableData = data.rows;
      this.tableTotal = data.records;
      this.tableLoading = false;
    },
    hanleSearch() {
      this.loadTablePageData();
    },

    async handleEnableChange(row) {
      await api.updateState(row.f_Id, row.f_EnabledMark);
      this.$message({
        type: "success",
        message: this.$t("更新成功!"),
      });
      this.updateModules();
    },
    handleDesign(item) {
      this.formEdit = true;
      this.formCopy = false;
      this.formEditRow = item;
      this.showForm("编辑桌面");
    },
    handleAdd() {
      this.formEdit = false;
      this.formCopy = false;
      this.showForm("新建桌面");
    },
    handleDelete(item) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"), 
        this.$t("提示"), {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.remove(item.f_Id).then(() => {
            this.$message({
              type: "success",
              message: this.$t("删除成功!"),
            });
            this.loadTablePageData();
            this.updateModules();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除"),
          });
        });
    },
    handleCopy(item) {
      this.formEdit = false;
      this.formCopy = true;
      this.formEditRow = item;
      this.showForm("新建桌面");
    },
    handleViews(item) {
      this.formEditRow = item;
      this.preveiwVisible = true;
    },
    handleHistory(item) {
      this.formEditRow = item;
      this.historyTitle = item.f_Name;
      this.schemeId = item.f_SchemeId;
      this.schemeInfoId = item.f_Id;

      this.historyVisible = true;
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },

    async handleSave(isNotClose) {
      const loading = this.$loading({
        lock: true,
        text: "正在保存配置，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
      });

      this.$nextTick(async () => {
        const postData = await this.$refs.form.getForm();
        let res = null;
        if (this.formEdit) {
          res = await this.$awaitWraper(
            api.update(this.formEditRow.f_Id, postData)
          );
        } else {
          res = await this.$awaitWraper(api.add(postData));
        }
        if (res) {
          this.$message({
            type: "success",
            message: this.formEdit ? this.$t("编辑成功!") : this.$t("新增成功!"),
          });
          if (isNotClose != true) {
            this.formVisible = false;
            this.loadTablePageData();
            this.updateModules();
          }
        }
        loading.close();
      });
    },

    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit || this.formCopy) {
        showLoading("加载数据中...");
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id));

        if (this.formCopy) {
          data.lr_desktop_infoEntity.f_Id = "";
          data.lr_desktop_infoEntity.f_ModuleId = "";
          data.lr_desktop_infoEntity.f_Code = `${data.lr_desktop_infoEntity.f_Code}-copy`;
          data.lr_desktop_infoEntity.f_Name = `${data.lr_desktop_infoEntity.f_Name}-复制`;
        }

        this.$refs.form.setForm(data);
        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    handleValidateSteps() {
      return this.$refs.form.validateSteps();
    },

    handleOpenedPreviewForm(showLoading, hideLoading) {
      showLoading("加载数据中...");
      this.$nextTick(async () => {
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id));
        this.$refs.previewForm.setForm(
          JSON.parse(data.lr_desktop_schemeEntity.f_Content)
        );
        hideLoading();
      });
    },
    handleClosePreviewForm() {
      this.$refs.previewForm.resetForm();
    },

    HistoryOpened() {
      this.$refs.HistoryForm.loadTablePageData();
    },
    updateSchemeId(id) {
      this.schemeId = id;
      this.formEditRow.f_SchemeId = id;
    },

    handleExport(row) {
      this.lr_downTempFile(
        `desktop/setting/download/desktop/${row.f_Id}`,
        `桌面_${row.f_Name}${row.f_Code}`,
        "desktop",
        "json"
      );
    },
    exportSuccess(){
        this.loadTablePageData();
    },
  },
};
</script>
<style lang="scss">
.l-desktop-setting-index {
  .l-panel--tool {
    border-bottom: 0;
  }

  .el-empty {
    position: absolute;
    margin-top: -145px;
    top: 50%;
    left: 0;
    width: 100%;
  }
}
</style>

